package com.yunchao.library.socket.extensions

import com.yunchao.library.socket.constants.Limits
import com.yunchao.library.socket.constants.Errors
import java.nio.ByteBuffer

fun ByteBuffer.putString(value: String) {
    val bytes = value.encodeToByteArray()
    require(bytes.size <= Limits.MAX_STRING_LENGTH) {
        "${Errors.STRING_TOO_LONG}: ${bytes.size} > ${Limits.MAX_STRING_LENGTH}"
    }
    putInt(bytes.size)
    put(bytes)
}

fun ByteBuffer.getString(): String {
    val length = int
    require(length in 0..Limits.MAX_STRING_LENGTH) {
        "${Errors.INVALID_STRING_LENGTH}: $length"
    }
    return ByteArray(length).also { get(it) }.decodeToString()
}

fun ByteBuffer.getByteArray(length: Int): ByteArray {
    require(length in 0..Limits.MAX_BYTE_ARRAY_SIZE) {
        "${Errors.INVALID_BYTE_ARRAY_LENGTH}: $length"
    }
    return ByteArray(length).also { get(it) }
}